#include <string.h>
#include <stdbool.h>
#include "string_tools.h"
#include "steggen_valid.h"

meta_error validate_meta_line(char* meta_line)
{
    const char *eq_pos = strchr(meta_line, '=');
    size_t len = strlen(meta_line);
    bool chk_failed = false;

    register unsigned int i;

    if (len < 6) // shortest possible string is !v="v"
        return M_INVALID_STR_LENGTH;
    for (i = 1; i < (eq_pos - meta_line); i++)
        if (isalpha_uscore(meta_line[i]) == 0)
            chk_failed = true;

    if (chk_failed == true)
        return M_INVALID_VAR_NAMING;

    if (chrn(meta_line, '=') != 1)
        return M_INVALID_EQ_SIGN_NUMBER;

    if (meta_line[1] == '=')
        return M_INVALID_EQ_SIGN_POS;

    if (chrn(meta_line, '"') != 2)
        return M_INVALID_QUOTATION_NUMBER;

    if (eq_pos[1] != '"' || meta_line[len-1] != '"')
        return M_INVALID_QUOTATION_POS;

    return M_OK;
}

array_error validate_array_line(char* array_line)
{
    const char *eq_pos = strchr(array_line, '=');
    size_t len = strlen(array_line);
    bool chk_failed = false;

    register unsigned int i;
    register unsigned int c = 0;

    if (len < 6)
        return A_INVALID_STR_LENGTH;
    for (i = 1; i < (eq_pos - array_line); i++)
        if (isalpha_uscore(array_line[i]) == 0)
            chk_failed = true;

    if (chk_failed == true)
        return A_INVALID_VAR_NAMING;

    if (chrn(array_line, '=') != 1)
        return A_INVALID_EQ_SIGN_NUMBER;

    if (array_line[1] == '=')
        return A_INVALID_EQ_SIGN_POS;

    if (chrn(array_line, '"') % 2 != 0)
        return A_INVALID_QUOTATION_NUMBER;

    if (array_line[len-1] != '"')
        return A_INVALID_QUOTATION_POS;

    for (i = 1; i < len; i++)
        if (array_line[i] == '"' && array_line[i - 1] == '"')
            return A_INVALID_VAL_LENGTH;

    if ((chrn(array_line, ',') + 1) * 2 != chrn(array_line, '"'))
            return A_INVALID_COMMA_NUMBER;

    while (array_line[i] != 0)
    {
        if (array_line[i] == '"')
            c++;

        if (array_line[i] == ',' && c % 2 != 0)
            return A_INVALID_COMMA_POS;

        i++;
    }

    return A_OK;
}